package com.monitor.config.yunke;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.monitor.commons.StringUtil;
import com.monitor.commons.enums.WhetherEnum;
import com.monitor.model.Dept;
import com.monitor.model.User;
import com.monitor.modelExt.DeptExt;
import com.monitor.modelExt.UserExt;
import lombok.Data;

import java.util.ArrayList;
import java.util.List;


public class DeptAndUser {


    // 存储分类结果的容器类
    public static class Result {
        private List<UserExt> users;
        private List<DeptExt> depts;

        public Result() {
            this.users = new ArrayList<>();
            this.depts = new ArrayList<>();
        }
    }

    // 递归分类方法
    public static DeptUserResult classifyByType(JSONObject data) {
        DeptUserResult result = new DeptUserResult();

        recursiveClassify(data, result);
        return result;
    }

    private static void recursiveClassify(JSONObject item, DeptUserResult result) {

        String type = item.getString("type");

        if ("USER".equals(type)) {
            UserExt user = new UserExt();
            String uid=item.getString("id");
            user.setIsBind(WhetherEnum.NO.getValue());
            if(StringUtil.isNotObjEmpty(uid)){
                user.setYkUserId(uid);
                user.setIsBind(WhetherEnum.YES.getValue());
            }
            user.setName(item.getString("name"));
            user.setPhone(item.getString("phone"));
            user.setYkDeptId(item.getString("yunkePid"));
            user.setYkId(item.getString("yunkeId"));
            user.setIsValid(item.getString("isValid"));
            user.setImei(item.getString("imei"));
            result.getUsers().add(user);
        } else if ("DEPT".equals(type)) {
            DeptExt dept = new DeptExt();
            dept.setName(item.getString("name"));
            dept.setParentId(item.getString("yunkePid"));
            dept.setYkId(item.getString("yunkeId"));
            result.getDepts().add(dept);

            // 递归处理子部门
            JSONArray subs = item.getJSONArray("sub");
            if (StringUtil.isNotObjEmpty(subs) && !subs.isEmpty()) {
                for (Object subItem : subs) {
                    recursiveClassify((JSONObject) subItem, result);
                }
            }
        }

    }

}
